const express = require('express');
const app = express();
const { baseUrl } = require('../contants');

// 配置服务器设置
const config = {
  port: 3000,
  host: '0.0.0.0', // 默认监听所有接口
  baseUrl: baseUrl || `http://localhost:3000`
}

const os = require('os');
// 获取本机IP地址
function getLocalIP() {
  const interfaces = os.networkInterfaces();
  for (const name of Object.keys(interfaces)) {
    for (const interface of interfaces[name]) {
      if (interface.family === 'IPv4' && !interface.internal) {
        return interface.address;
      }
    }
  }
  return 'localhost'
}
const localIP = getLocalIP()

// 添加CORS中间件
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, token');
  // 处理预检请求
  if (req.method === 'OPTIONS') {
    res.sendStatus(200);
  } else {
    next()
  }
});


// 中间件
app.use(express.json());
app.use(express.urlencoded({ extended: true }));


// 引入路由
const detailRouter = require('./routes/sys/detail/detail');
const loginRouter = require('./routes/sys/user/login');
const paperRouter = require('./routes/paper/paper');
const examRouter = require('./routes/exam/exam');
const myPagingRouter = require('./routes/user/my-paging');
const quRouter = require('./routes/qu/qu')
const workBookRouter = require('./routes/user/wrong-book')

const saveRouter = require('./routes/repo/save')
const repoPagingRouter = require('./routes/repo/paging')
const repoDeleteRouter = require('./routes/repo/delete')
const repoDetailRouter = require('./routes/repo/detail')
const repoBatchRouter = require('./routes/repo/batch-action')
const exportRouter = require('./routes/qu/export')
const importRouter = require('./routes/qu/import')
const userPagingRouter = require('./routes/sys/user/paging')
const regRouter = require('./routes/sys/user/reg')
const configRouter = require('./routes/sys/config/save')
const rolePagingRouter = require('./routes/sys/role/paging')
const departPagingRouter = require('./routes/sys/depart/paging')
const userUpdateRouter = require('./routes/sys/user/update')
const heartbeatRouter = require('./routes/user/heartbeat')


// 定义所有路由模块
const routeModules = [
  detailRouter,
  loginRouter,
  paperRouter,
  examRouter,
  myPagingRouter,
  quRouter,
  workBookRouter,
  saveRouter,
  repoPagingRouter,
  repoDeleteRouter,
  repoDetailRouter,
  repoBatchRouter,
  exportRouter, importRouter,
  userPagingRouter,
  regRouter, configRouter, rolePagingRouter, departPagingRouter, userUpdateRouter,
  heartbeatRouter
]

// 批量注册路由
routeModules.forEach(router => {
  app.use('/exam/api', router)
})

//上传文件路由
const uploadRouter = require('./routes/common/file/upload')
app.use('/common/api', uploadRouter)

//添加定时任务相关代码
const Scheduler = require('./scheduler/scheduler')
let scheduler = null

// 启动服务器
app.listen(config.port, config.host, () => {
  console.log(`🚀 服务器已启动`);
  console.log(`📍 本地访问: http://localhost:${config.port}`)
  console.log(`🌐 网络访问: http://${localIP}:${config.port}`)
  console.log(`🔗 API基础地址: ${config.baseUrl}`)

  console.log('\n')
  // 初始化定时任务
  try {
    scheduler = new Scheduler();
    scheduler.init();
    console.log('✅ 定时任务系统启动成功');
  } catch (error) {
    console.error('❌ 定时任务系统启动失败:', error);
  }
});